package main.com.votes.controller;

import com.sun.corba.se.spi.ior.iiop.IIOPFactories;
import com.sun.org.apache.bcel.internal.generic.NEW;
import main.com.votes.dao.ArticleDao;
import main.com.votes.dao.OptionDao;
import main.com.votes.dao.VoteDao;
import main.com.votes.model.Article;
import main.com.votes.model.Vote;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/articleListServlet")
public class ArticleListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    ArticleDao articleDao = new ArticleDao();
    VoteDao voteDao = new VoteDao();


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); // 设置请求编码为UTF-8
        response.setCharacterEncoding("UTF-8"); // 设置响应编码为UTF-8
        // 获取 session
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        
        // 检查用户是否已登录
        if (username == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String flag = request.getParameter("flag");

        if ("add".equals(flag)) {
            // 获取表单数据
            String title = request.getParameter("title");
            String type = request.getParameter("type");
            String[] options = request.getParameterValues("option");

            // 在这里可以根据需要处理表单提交的数据，比如存入数据库等操作
            // 以下为示例，假设输出到控制台
            System.out.println("标题: " + title);
            System.out.println("类型: " + type);
            int update = articleDao.addArticle(title, type,request);
            OptionDao optionDao = new OptionDao();
            if (update == 1) {
                Article article = articleDao.getOne(title, type);
                System.out.println("选项:");
                for (String option : options) {
//                    写入选项
                    optionDao.addOption(article.getArticleid(), option);
                }
            }
            // 可以设置一些成功的提示信息，然后重定向到成功页面或者刷新当前页面
            session.setAttribute("msg", "新增投票OK");
            response.sendRedirect(request.getContextPath() + "/admin/addNewtp.jsp");
        } else if ("search".equals(flag)){
//            查询
            String key = request.getParameter("key");
            List<Article> list = articleDao.selectByTitle(key);

            for (Article article : list) {
                Vote vote = voteDao.isIHaveVote(article.getArticleid(), request);
                if (vote != null) {
//                    已投过
                    article.setNum(1);
                } else {
                    article.setNum(0);
                }
                article.setVoteNum(articleDao.getVoteCount(article.getArticleid()));
            }
            // 设置 request 属性
            request.setAttribute("list", list);
            request.setAttribute("head", "首页");
            request.setAttribute("tail", "尾页");

            // 转发请求到 JSP 页面
            request.getRequestDispatcher("admin/index.jsp").forward(request, response);
        } else if ("me".equals(flag)) {
//            我创建的投票
            String key = request.getParameter("key");
            List<Article> list = articleDao.selectCreateByMe(request);

            for (Article article : list) {
                Vote vote = voteDao.isIHaveVote(article.getArticleid(), request);
                if (vote != null) {
//                    已投过
                    article.setNum(1);
                } else {
                    article.setNum(0);
                }
                article.setVoteNum(articleDao.getVoteCount(article.getArticleid()));
            }
            // 设置 request 属性

            request.setAttribute("list", list);
            request.setAttribute("head", "首页");
            request.setAttribute("tail", "尾页");
            request.setAttribute("del", true);

            // 转发请求到 JSP 页面
            request.getRequestDispatcher("admin/index.jsp").forward(request, response);
        }else if ("del".equals(flag)) {
//        删除
            String articleId = request.getParameter("articleid");
            PrintWriter out = response.getWriter();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            try {
                // Call your service layer to delete the article
                int isDeleted = articleDao.deleteArticle(articleId);

                if (isDeleted==1) {
                    out.print("{\"status\":\"success\"}");
                } else {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print("{\"status\":\"error\",\"message\":\"删除失败\"}");
                }
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"status\":\"error\",\"message\":\"服务器内部错误\"}");
                e.printStackTrace();
            } finally {
                out.flush();
                out.close();
            }
        }
        else {
            // 处理其他操作，比如删除等
            // 可根据需要添加逻辑
            // 获取请求参数

            String goPageStr = request.getParameter("goPage");
            int goPage = goPageStr != null ? Integer.parseInt(goPageStr) : 1;



            List<Article> list = articleDao.getArticles();

            for (Article article : list) {
                Vote vote = voteDao.isIHaveVote(article.getArticleid(), request);
                if (vote != null) {
//                    已投过
                    article.setNum(1);
                } else {
                    article.setNum(0);
                }
                article.setVoteNum(articleDao.getVoteCount(article.getArticleid()));
            }
//        分页
//        PageBeanUtils<Article> pageBeanUtils = new PageBeanUtils<>(goPage-1,goPage+1,1, )

            // 设置 request 属性
            request.setAttribute("list", list);
            request.setAttribute("goPage", goPage);
            request.setAttribute("head", "首页");
            request.setAttribute("tail", "尾页");

            // 转发请求到 JSP 页面
            request.getRequestDispatcher("admin/index.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
